<?php
/**
 * Fastapp.
 * 7/19/24
 * @Author deepsea
 * @Contact telegram:deepsea159
 */

namespace App\Fastapp\Api\Controller\Wechat;

use App\Fastapp\Api\Controller\ApiController;
use App\Fastapp\Api\Service\Wechat\MpService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Psr\Http\Message\ResponseInterface;

#[Controller('api/wechat/mp')]
class MpController extends ApiController
{
    #[Inject]
    public MpService $service;

    #[GetMapping('getRedirectUrl')]
    public function getRedirectUrl(): ResponseInterface
    {
        return $this->success($this->service->getRedirectUrl($this->validate(['to_url' => 'required|string', 'scope' => 'string'])));
    }

    #[GetMapping('redirectTo')]
    public function redirectTo(): ResponseInterface
    {
        $data = $this->request->all();
        $url = $data['r'];
        unset($data['r']);
        if ($data) {
            if (str_contains($url, '?')) $url .= '&'; else $url .= '?';
            $url .= http_build_query($data);
        }
        return $this->redirect($url);
    }

    #[PostMapping('login')]
    public function login(): ResponseInterface
    {
        return $this->success($this->service->login($this->validate(['code' => 'string'])));
    }
}